package com.acane.instagram.feature.post

import android.content.Context
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.Tag
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.me.MeViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.IOException

class PostViewModel(
): ViewModel() {

    var selectedImageUris by mutableStateOf<List<Uri>>(emptyList())
    var caption by mutableStateOf("")
    var location by mutableStateOf("")

    val _shareRange = MutableStateFlow<String>("public")
    val shareRange: MutableStateFlow<String> = _shareRange
    // 更改shareRange方法
    fun updateShareRange(newValue: String) {
        _shareRange.value = newValue
    }
    val _showRange = MutableStateFlow<String>("grid_and_reels")
    val showRange: MutableStateFlow<String> = _showRange
    // 更改showRange方法
    fun updateShowRange(newValue: String) {
        _showRange.value = newValue
    }
    //  设置tags最大容量为3

    private val _tags = MutableStateFlow<List<Tag>>(emptyList())
    val tags: MutableStateFlow<List<Tag>> = _tags

    // 往_tags添加数据
    fun addTag(tag: Tag) {
        _tags.value = _tags.value + tag
    }
    // 移除_tags的数据
    fun removeTag(tag: Tag) {
        _tags.value = _tags.value - tag
    }

    private val _recommendedTags = MutableStateFlow<List<Tag>>(emptyList())
    val recommendedTags: MutableStateFlow<List<Tag>> = _recommendedTags

    suspend fun getTagTestData() {
        //tags.value = listOf("tag1", "tag2", "tag3")
        recommendedTags.value = MyRetrofitDatasource.getTagList().data!!
    }

    var uploadUris = mutableStateOf<List<String>>(emptyList())
    fun setSelectedImages(uris: List<Uri>) {
        selectedImageUris = uris
    }
    private val _postDatum = MutableStateFlow<List<PostInfo>>(emptyList())
    val postDatum: MutableStateFlow<List<PostInfo>> = _postDatum

    init {

    }

     fun initPostData(userId: String?) {
        viewModelScope.launch {
            loadPostData(userId).join() // 等待数据加载完成
        }
    }
    private fun loadPostData(userId: String?): Job = viewModelScope.launch {
        Log.d("MeViewModel", "开始初始化数据")
        val newData = userId.let {
            try {
                it?.let { it1 -> MyRetrofitDatasource.getPostListById(it1).data }
            } catch (e: Exception) {
                Log.e("MeViewModel", "网络请求失败", e)
                emptyList<PostInfo>()
            }
        } ?: emptyList()
        _postDatum.value = newData
    }


// PostViewModel.kt
fun postContent(context: Context, meViewModel: MeViewModel) {  // 添加meViewModel参数
    viewModelScope.launch {
        val isUploaded = uploadFiles(selectedImageUris, context)
        if (isUploaded) {
            uploadPost(context)
            // 触发数据刷新
            meViewModel.refreshPosts()
        }
    }
}

    private fun uploadPost(context: Context) {
        viewModelScope.launch {
            val hasSensitive = MyRetrofitDatasource.checkSensitive(caption).data
            if (hasSensitive == true) {
                // 弹出提示：消息包含敏感词，请修改
                Toast.makeText(context, "帖子含敏感词，请修改", Toast.LENGTH_SHORT).show()
                return@launch
            }
        }
        val thumbnailUrl = uploadUris.value.firstOrNull() ?: ""
        val postInfo = PostInfo(
            id = "",
            user = SessionManager.currentUser!!,
            content = caption,
            urls = uploadUris.value,
            likeCount = 0,
            commentCount = 0,
            createdTime = null,
            shareRange = shareRange.value,
            showRange = showRange.value,
            thumbnailUrl = thumbnailUrl,
            tags = tags.value
        )
        viewModelScope.launch {
        Log.d("PostViewModel", "前端发送的post数据: $postInfo")
            val response = MyRetrofitDatasource.createNewPost(postInfo).data
            Log.d("PostViewModel", "uploadPost: $response")
        }
    }




    private suspend fun uploadFiles(uris: List<Uri>, context: Context): Boolean {
        val serverFileNames = mutableListOf<String>()
        uris.forEach { uri ->
            val filePart = uri.toMultipartBodyPart(
                context = context,
                partName = "file",
                fileName = null
            )
            val response = MyRetrofitDatasource.uploadMedia(
                file = filePart
            )
            Log.d("PostViewModel", "uploadMsg: ${response}")
            val serverFileName = response.data
            serverFileName?.let { serverFileNames.add(it) }
        }
        withContext(Dispatchers.Main) {
            uploadUris.value = serverFileNames
        }
        Log.d("PostViewModel", "uploadFiles: ${uploadUris.value}")
        return uploadUris.value.isNotEmpty()
    }

    private fun Uri.toMultipartBodyPart(
        context: Context,
        partName: String,
        fileName: String? // 允许传递null
    ): MultipartBody.Part {
        return context.contentResolver.openInputStream(this)?.use { stream ->
            // 获取实际MIME类型
            val mimeType = context.contentResolver.getType(this) ?: "application/octet-stream"
            val requestBody = stream.readBytes().toRequestBody(mimeType.toMediaType())

            // 如果fileName为null，由后端决定文件名
            MultipartBody.Part.createFormData(
                partName,
                fileName ?: "", // 空文件名让后端处理
                requestBody
            )
        } ?: throw IOException("无法读取文件")
    }

//    fun sendComment(postId: String, content: String) {
//        viewModelScope.launch {
//            MyRetrofitDatasource.createNewComment(
//                CommentDTO(
//                    id = "",
//                    commenterId = SessionManager.currentUser?.id ?: "",
//                    postId = postId,
//                    content = content,
//                    timestamp = "" // 根据实际需求生成时间戳
//                )
//            )
//        }
//    }
}
